package net.lovesrc.allin.biz.stl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import net.lovesrc.allin.Message;
import net.lovesrc.allin.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/stl")
public class StlController extends BaseController {

    @Autowired
    private StlService stlService;

    @Autowired
    private StlRegisterService stlRegisterService;

    @GetMapping("/new-register")
    public Message newRegister(@RequestParam(required = false, defaultValue = StringUtils.EMPTY) String promotionCode) {
        String newMobile = stlRegisterService.newRegister(promotionCode);
        return Message.success(newMobile);
    }

    @GetMapping("/auth-id")
    public Message authId(String mobile) {
        stlRegisterService.authId(mobile);
        return Message.success();
    }

    @GetMapping("/sync-status")
    public Message syncStatus(String mobile) {
        stlRegisterService.syncStatus(mobile);
        return Message.success();
    }

    @GetMapping("/profit")
    public Message profit(String mobile) {
        stlService.profit(mobile);
        return Message.success();
    }

    @GetMapping("/profits")
    public Message profits() {
        stlService.profits(3000);
        return Message.success();
    }

    @PostMapping("/new-my-jy")
    public Message newJy(String buyerMobile, String sellerMobile, String autoSelectSeller) {
        boolean autoSelect = "on".equalsIgnoreCase(autoSelectSeller);
        if (autoSelect) {
            stlService.newToMyJyWithAutoSelectSeller(getCurrentUserId(), buyerMobile);
        } else {
            stlService.newJy(getCurrentUserId(), "ManualJy", buyerMobile, sellerMobile);
        }
        return Message.success();
    }

    @PostMapping("/new-sys-jy")
    public Message newSysJy() {
        stlService.newSysJy(getCurrentUserId());
        return Message.success();
    }

    @PostMapping("/new-sys-jy-4-sell")
    public Message newSysJy4Sell() {
        stlService.autoSysJy4Sell(getCurrentUserId());
        return Message.success();
    }

    @GetMapping("/pre-pay-jy")
    public Message prePayJy(Integer jyId) {
        JSONObject jyRow = queryForRow(jdbcTemplate, "select * from t_stl_jy where jyId = ?", jyId);
        String sellerMobile = jyRow.getString("sellerMobile");
        JSONObject seller = queryForRow(jdbcTemplate, "select * from t_stl_account where mobile = ?", sellerMobile);
        File file = stlService.jieTu(jyId, false);
        String imageUrl = "/jietu/" + file.getName() + "?v=" + new Date().getTime();
        JSONObject result = new JSONObject()
                .fluentPut("imageUrl", imageUrl)
                .fluentPut("amount", jyRow.getBigDecimal("amount"))
                .fluentPut("sellerName", seller.getString("realName"));
        return Message.success(result);
    }

    @PostMapping("/refresh-jy-jietu")
    public Message refreshJyJieTu(Integer jyId) {
        File file = stlService.jieTu(jyId, true);
        String imageUrl = "/jietu/" + file.getName() + "?v=" + new Date().getTime();
        return Message.success(imageUrl);
    }

    @PostMapping("/pay-jy")
    public Message payJy(Integer jyId, MultipartFile payImg) throws IOException {
        if (payImg == null || payImg.isEmpty()) {
            stlService.payJyWithAutoJieTu(jyId);
        } else {
            File payImageFile = new File(SystemUtils.getJavaIoTmpDir(), UUID.randomUUID().toString());
            payImg.transferTo(payImageFile);
            stlService.payJy(jyId, payImageFile);
        }
        return Message.success();
    }

    @PostMapping("/confirm-jy")
    public Message confirmJy(Integer jyId) {
        stlService.confirmJY(jyId);
        return Message.success();
    }

    @PostMapping("/sync-my-account")
    public Message syncMyAccount() {
        List<JSONObject> rows = queryForRows(jdbcTemplate, "select mobile from v_stl_my_account");
        for (JSONObject row : rows) {
            String mobile = row.getString("mobile");
            stlService.profit(mobile);
        }
        return Message.success();
    }

    @GetMapping("/once")
    public Message once() throws IOException {
        stlService.once();
        return Message.success();
    }

    @GetMapping("/mobile-status")
    public Message mobileStatus() {
        stlService.updateMobileStatus();
        return Message.success();
    }

    @GetMapping("/test")
    public Message getUserInfo(String mobile) {
        stlService.profit(mobile);
        return Message.success();
    }

    @PostMapping("/new-sell-auto-pay-account")
    public Message newSellAutoPayAccount() {
        stlService.newSell(getCurrentUserId());
        return Message.success();
    }

    @PostMapping("/new-sell")
    public Message newSell(String alipayAccountId) {
        stlService.newSell(getCurrentUserId(), alipayAccountId);
        return Message.success();
    }

    @PostMapping("/cancel-sell")
    public Message cancelSell(Long id) {
        stlService.cancelSell(id);
        return Message.success();
    }

    @PostMapping("/make-sell-jy")
    public Message makeSellJy(Long id) {
        stlService.makeSellJy(id);
        return Message.success();
    }

    @PostMapping("/sync-sell-jy-status")
    public Message syncSellJyStatus() {
        stlService.syncSellJyStatus(false);
        return Message.success();
    }

    @PostMapping("/confirm-sell-jy")
    public Message confirmSellJY(Integer jyId) {
        stlService.confirmSellJY(getCurrentUserId(), jyId);
        return Message.success();
    }

    @PostMapping("/force-set-sell-new-alipay")
    public Message forceSetSellNewAlipay(Long id, String alipayAccountId) {
        stlService.forceSetSellNewAlipay(id, alipayAccountId);
        return Message.success();
    }

    @PostMapping("/ing-orders")
    public Message ingOrders(String mobile) {
        return Message.success(stlService.getIngJyList(mobile));
    }

    @GetMapping("/qiang")
    public Message qiang(String sellerMobile, String qtys) {
        List<Integer> intQtys = Splitter.on(",")
                .trimResults()
                .splitToList(qtys)
                .stream()
                .map(r -> Integer.valueOf(r))
                .collect(Collectors.toList());
        stlService.bidJy(sellerMobile, intQtys, true);
        return Message.success();
    }

}